/**
 * @description 网络请求
 */
import axios from 'axios';
import store from '../store';
import { Notify, Toast } from "vant";
import router from '../router'

export const request = (config) => {
    const instance = axios.create({
        baseURL: 'https://api.shop.eduwork.cn',
        timeout: 5000
    });

    // 请求拦截
    instance.interceptors.request.use(config => {
        // 接口认证设置
        const Token = store.state.Token
        const Token_type = store.state.Token_type || 'Bearer'
        if (Token) {
            config.headers.Authorization = `${Token_type} ${Token}`
        }
        store.commit('showLoading')
        return config;
    }, err => {
        store.commit('hideLoading')
        console.log('请求拦截Error:', err);
    })

    // 响应拦截
    instance.interceptors.response.use(res => {
        store.commit('hideLoading')
        return res.data ? res.data : res;
    }, err => {
        // 如果接口需要认证 则跳转到登录页授权
        store.commit('hideLoading')
        console.log('响应拦截Error:', err.response.data);
        if (err.response.status === 401) {
            Toast.fail('请登录')
            router.push('/register')
        }
        Notify(err.response.data)
    })

    return instance(config);
}